using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.ManagedClient;
using BanZuiCloudControlAgent.Core.Mqtt.Models;
using BanZuiCloudControlAgent.Utils.Exceptions;
using BanZuiCloudControlAgent.Utils.Logging;

namespace BanZuiCloudControlAgent.Core.Mqtt
{
    /// <summary>
    /// MQTT客户端管理器，负责管理MQTT客户端连接
    /// </summary>
    public class MqttClientManager : IDisposable
    {
        private readonly NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
        private IManagedMqttClient _managedClient;
        private MqttClientOptions _options;
        private MqttTopics _mqttTopics;
        private bool _isConnected;
        private int _reconnectAttempts;
        private readonly SemaphoreSlim _connectionLock = new SemaphoreSlim(1, 1);
        private bool _manualDisconnect; // 手动断开连接标志

        /// <summary>
        /// 连接状态变更事件
        /// </summary>
        public event EventHandler<MqttConnectionStatusChangedEventArgs> ConnectionStatusChanged;

        /// <summary>
        /// 消息接收事件
        /// </summary>
        public event EventHandler<MqttMessageReceivedEventArgs> MessageReceived;

        /// <summary>
        /// 是否已连接
        /// </summary>
        public bool IsConnected => _isConnected;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="options">MQTT客户端选项</param>
        public MqttClientManager(MqttClientOptions options)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            _mqttTopics = new MqttTopics(_options.TopicPrefix, _options.DeviceCode);
            _isConnected = false;
            _reconnectAttempts = 0;
            _manualDisconnect = false;
        }

        /// <summary>
        /// 初始化MQTT客户端
        /// </summary>
        public async Task InitializeAsync()
        {
            try
            {
                _logger.Info($"初始化MQTT客户端 - 服务器: {_options.ServerUrl}:{_options.ServerPort}, 设备码: {_options.DeviceCode}, 用户名:{_options.Username} 密码:{_options.Password}");

                // 创建MQTT客户端工厂
                var factory = new MqttFactory();

                // 创建托管MQTT客户端
                _managedClient = factory.CreateManagedMqttClient();

                // 设置事件处理程序
                _managedClient.ConnectedAsync += OnConnectedAsync;
                _managedClient.DisconnectedAsync += OnDisconnectedAsync;
                _managedClient.ApplicationMessageReceivedAsync += OnApplicationMessageReceivedAsync;

                // 创建MQTT客户端选项
                var clientOptions = new MqttClientOptionsBuilder()
                    .WithClientId(_options.ClientId)
                    .WithTcpServer(_options.ServerUrl, _options.ServerPort)
                    .WithCredentials(_options.Username, _options.Password)
                    .WithCleanSession(_options.CleanSession)
                    .WithKeepAlivePeriod(TimeSpan.FromSeconds(_options.KeepAliveInterval));

                // 配置TLS
                if (_options.UseTls)
                {
                    clientOptions = clientOptions.WithTls();
                }

                // 配置遗嘱消息
                var disconnectMessage = CreateDisconnectMessage();
                clientOptions = clientOptions.WithWillPayload(disconnectMessage)
                    .WithWillTopic(_mqttTopics.WillMessage)
                    .WithWillQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                    .WithWillRetain(false);

                // 创建托管客户端选项
                var managedOptions = new ManagedMqttClientOptionsBuilder()
                    .WithAutoReconnectDelay(TimeSpan.FromSeconds(_options.AutoReconnectDelay))
                    .WithClientOptions(clientOptions.Build())
                    .Build();

                // 启动客户端
                // await _managedClient.StartAsync(managedOptions);

                _logger.Info("MQTT客户端初始化完成");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "初始化MQTT客户端失败");
                throw new EmqxException(EmqxErrorType.ConnectionFailed, null, "初始化MQTT客户端失败", ex);
            }
        }

        /// <summary>
        /// 连接到MQTT服务器
        /// </summary>
        public async Task ConnectAsync()
        {
            try
            {
                await _connectionLock.WaitAsync();

                if (_managedClient == null)
                {
                    await InitializeAsync();
                }

                // 检查客户端是否已启动
                if (_managedClient.IsStarted)
                {
                    _logger.Info("MQTT客户端已经启动，无需重复连接");
                    return;
                }

                _logger.Info("开始连接到MQTT服务器");

                // 创建托管客户端选项
                var clientOptions = new MqttClientOptionsBuilder()
                    .WithClientId(_options.ClientId)
                    .WithTcpServer(_options.ServerUrl, _options.ServerPort)
                    .WithCredentials(_options.Username, _options.Password)
                    .WithCleanSession(_options.CleanSession)
                    .WithKeepAlivePeriod(TimeSpan.FromSeconds(_options.KeepAliveInterval));

                if (_options.UseTls)
                {
                    clientOptions = clientOptions.WithTls();
                }

                var disconnectMessage = CreateDisconnectMessage();
                clientOptions = clientOptions.WithWillPayload(disconnectMessage)
                    .WithWillTopic(_mqttTopics.WillMessage)
                    .WithWillQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                    .WithWillRetain(false);

                var managedOptions = new ManagedMqttClientOptionsBuilder()
                    .WithAutoReconnectDelay(TimeSpan.FromSeconds(_options.AutoReconnectDelay))
                    .WithClientOptions(clientOptions.Build())
                    .Build();

                // 启动客户端
                await _managedClient.StartAsync(managedOptions);
                _logger.Info("MQTT客户端已启动并开始连接");
            }
            catch (InvalidOperationException ex) when (ex.Message.Contains("already started"))
            {
                _logger.Warn("MQTT客户端已经启动，忽略重复连接请求");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "连接到MQTT服务器失败");
                throw new EmqxException(EmqxErrorType.ConnectionFailed, null, "连接到MQTT服务器失败", ex);
            }
            finally
            {
                _connectionLock.Release();
            }
        }

        /// <summary>
        /// 断开与MQTT服务器的连接
        /// </summary>
        /// <param name="isCancelReconnect">是否是取消重连</param>
        /// <param name="isClosing">是否在应用程序关闭过程中</param>
        public async Task DisconnectAsync(bool isCancelReconnect = false, bool isClosing = false)
        {
            try
            {
                await _connectionLock.WaitAsync();

                if (_managedClient == null)
                {
                    _logger.Warn("MQTT客户端未初始化，无法断开连接");
                    return;
                }

                if (!_managedClient.IsStarted)
                {
                    _logger.Warn("MQTT客户端未启动，无需断开连接");
                    return;
                }

                // 设置手动断开标志，除非是取消重连或应用程序关闭
                _manualDisconnect = !isCancelReconnect && !isClosing;
                
                if (isCancelReconnect)
                {
                    _logger.Info($"取消重连，当前重连尝试次数: {_reconnectAttempts}");
                }
                else
                {
                    _logger.Info($"断开MQTT连接，手动断开标志: {_manualDisconnect}");
                }
                
                await _managedClient.StopAsync();
                _isConnected = false;
                _reconnectAttempts = 0; // 重置重连尝试次数
                
                // 触发连接状态变更事件，但在应用程序关闭时不触发
                if (!isClosing)
                {
                    if (isCancelReconnect)
                    {
                        OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(false, "用户取消重连"));
                        _logger.Info("已取消重连");
                    }
                    else
                    {
                        OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(false, "主动断开连接"));
                        _logger.Info("MQTT连接已断开");
                    }
                }
                else
                {
                    _logger.Info("应用程序关闭过程中断开MQTT连接，不触发状态事件");
                }
            }
            catch (Exception ex)
            {
                if (isCancelReconnect)
                {
                    _logger.Error(ex, "取消重连失败");
                    throw new EmqxException(EmqxErrorType.DisconnectionFailed, null, "取消重连失败", ex);
                }
                else
                {
                    _logger.Error(ex, "断开MQTT连接失败");
                    throw new EmqxException(EmqxErrorType.DisconnectionFailed, null, "断开MQTT连接失败", ex);
                }
            }
            finally
            {
                _connectionLock.Release();
            }
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="payload">消息内容</param>
        /// <param name="qosLevel">服务质量级别</param>
        /// <param name="retain">是否保留消息</param>
        public async Task PublishAsync(string topic, string payload, int qosLevel = 0, bool retain = false)
        {
            try
            {
                if (_managedClient == null || !_isConnected)
                {
                    throw new EmqxException(EmqxErrorType.NotConnected, topic, "MQTT客户端未连接");
                }

                var message = new MqttApplicationMessageBuilder()
                    .WithTopic(topic)
                    .WithPayload(payload)
                    .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qosLevel)
                    .WithRetainFlag(retain)
                    .Build();

                await _managedClient.EnqueueAsync(message);
                _logger.Debug($"已发布消息到主题: {topic}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"发布消息到主题 {topic} 失败");
                throw new EmqxException(EmqxErrorType.PublishFailed, topic, $"发布消息到主题 {topic} 失败", ex);
            }
        }

        /// <summary>
        /// 发布消息
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="payload">消息内容</param>
        /// <param name="qosLevel">服务质量级别</param>
        /// <param name="retain">是否保留消息</param>
        public async Task PublishAsync(string topic, byte[] payload, int qosLevel = 0, bool retain = false)
        {
            try
            {
                if (_managedClient == null || !_isConnected)
                {
                    throw new EmqxException(EmqxErrorType.NotConnected, topic, "MQTT客户端未连接");
                }

                var message = new MqttApplicationMessageBuilder()
                    .WithTopic(topic)
                    .WithPayload(payload)
                    .WithQualityOfServiceLevel((MQTTnet.Protocol.MqttQualityOfServiceLevel)qosLevel)
                    .WithRetainFlag(retain)
                    .Build();

                await _managedClient.EnqueueAsync(message);
                _logger.Debug($"已发布消息到主题: {topic}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"发布消息到主题 {topic} 失败");
                throw new EmqxException(EmqxErrorType.PublishFailed, topic, $"发布消息到主题 {topic} 失败", ex);
            }
        }

        /// <summary>
        /// 发布基于BaseMessageModel的消息
        /// </summary>
        /// <typeparam name="T">消息类型</typeparam>
        /// <param name="message">消息对象</param>
        /// <param name="qosLevel">服务质量级别</param>
        /// <param name="retain">是否保留消息</param>
        public async Task PublishMessageAsync<T>(T message, int qosLevel = 0, bool retain = false) where T : BaseMessageModel
        {
            try
            {
                if (message == null)
                {
                    throw new ArgumentNullException(nameof(message));
                }

                // 获取消息类型对应的主题
                string topic = _mqttTopics.GetPublishTopicByMessageType(message.MessageType);

                // 序列化消息
                string payload = Utils.Common.JsonHelper.Serialize(message);

                // 发布消息
                await PublishAsync(topic, payload, qosLevel, retain);
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"发布消息 {typeof(T).Name} 失败");
                throw new EmqxException(EmqxErrorType.PublishFailed, null, $"发布消息 {typeof(T).Name} 失败", ex);
            }
        }

        /// <summary>
        /// 订阅主题
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="qosLevel">服务质量级别</param>
        public async Task SubscribeAsync(string topic, int qosLevel = 1)
        {
            try
            {
                if (_managedClient == null || !_isConnected)
                {
                    throw new EmqxException(EmqxErrorType.NotConnected, topic, "MQTT客户端未连接");
                }

                await _managedClient.SubscribeAsync(topic, (MQTTnet.Protocol.MqttQualityOfServiceLevel)qosLevel);
                _logger.Info($"已订阅主题: {topic}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"订阅主题 {topic} 失败");
                throw new EmqxException(EmqxErrorType.SubscribeFailed, topic, $"订阅主题 {topic} 失败", ex);
            }
        }

        /// <summary>
        /// 取消订阅主题
        /// </summary>
        /// <param name="topic">主题</param>
        public async Task UnsubscribeAsync(string topic)
        {
            try
            {
                if (_managedClient == null || !_isConnected)
                {
                    throw new EmqxException(EmqxErrorType.NotConnected, topic, "MQTT客户端未连接");
                }

                await _managedClient.UnsubscribeAsync(topic);
                _logger.Info($"已取消订阅主题: {topic}");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, $"取消订阅主题 {topic} 失败");
                throw new EmqxException(EmqxErrorType.UnsubscribeFailed, topic, $"取消订阅主题 {topic} 失败", ex);
            }
        }

        /// <summary>
        /// 订阅设备需要的所有主题
        /// </summary>
        public async Task SubscribeToDeviceTopicsAsync()
        {
            try
            {
                if (_managedClient == null || !_isConnected)
                {
                    throw new EmqxException(EmqxErrorType.NotConnected, null, "MQTT客户端未连接");
                }

                foreach (var topic in _mqttTopics.GetSubscribeTopics())
                {
                    await SubscribeAsync(topic);
                }

                _logger.Info("已订阅设备所需的所有主题");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "订阅设备主题失败");
                throw new EmqxException(EmqxErrorType.SubscribeFailed, null, "订阅设备主题失败", ex);
            }
        }

        /// <summary>
        /// 更新MQTT客户端选项
        /// </summary>
        /// <param name="options">新的MQTT客户端选项</param>
        public void UpdateOptions(MqttClientOptions options)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            _mqttTopics = new MqttTopics(_options.TopicPrefix, _options.DeviceCode);
            _logger.Info($"已更新MQTT客户端选项 - 服务器: {_options.ServerUrl}:{_options.ServerPort}, 设备码: {_options.DeviceCode}, 用户名: {_options.Username}");
        }

        /// <summary>
        /// 连接成功事件处理
        /// </summary>
        private async Task OnConnectedAsync(MqttClientConnectedEventArgs e)
        {
            try
            {
                _isConnected = true;
                _reconnectAttempts = 0; // 重置重连尝试次数

                _logger.Info("已连接到MQTT服务器");

                // 订阅设备需要的主题
                await SubscribeToDeviceTopicsAsync();

                // 触发连接状态变更事件
                _logger.Debug("准备触发连接状态变更事件: IsConnected=true");
                OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(true));
                _logger.Debug("已触发连接状态变更事件: IsConnected=true");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "处理MQTT连接成功事件失败");
            }
        }

        /// <summary>
        /// 断开连接事件处理
        /// </summary>
        private Task OnDisconnectedAsync(MqttClientDisconnectedEventArgs e)
        {
            try
            {
                _isConnected = false;
                
                // 检查是否为手动断开
                if (_manualDisconnect)
                {
                    _logger.Info("检测到手动断开连接，不执行重连逻辑");
                    
                    // 触发断开连接事件，但不增加重连次数
                    OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(false, "用户手动断开连接", 0));
                    
                    // 重置手动断开标志
                    _manualDisconnect = false;
                    
                    return Task.CompletedTask;
                }
                
                // 非手动断开，增加重连次数
                _reconnectAttempts++;

                _logger.Warn($"与MQTT服务器断开连接，原因: {e.ReasonString}, 重连尝试次数: {_reconnectAttempts}");

                // 确保有人订阅事件
                if (ConnectionStatusChanged != null)
                {
                    _logger.Debug($"ConnectionStatusChanged事件有{ConnectionStatusChanged.GetInvocationList().Length}个订阅者");
                }
                else
                {
                    _logger.Warn("ConnectionStatusChanged事件没有订阅者，无法通知UI更新状态");
                }

                // 检查是否达到最大重连尝试次数
                bool maxReconnectReached = _options.MaxReconnectAttempts > 0 && _reconnectAttempts >= _options.MaxReconnectAttempts;
                
                if (maxReconnectReached)
                {
                    _logger.Info($"达到最大重连尝试次数 {_options.MaxReconnectAttempts}，重置计数器并继续尝试重连");
                    
                    // 重置重连计数器，实现永不放弃的重连策略
                    _reconnectAttempts = 0;
                    
                    // 触发特殊的断开连接事件，表示已重置重连次数
                    OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(false, $"已重置重连计数器，继续尝试重连", 0));
                }
                else
                {
                    // 触发普通断开连接事件
                    _logger.Debug($"触发断开连接事件: ReconnectAttempts={_reconnectAttempts}");
                    OnConnectionStatusChanged(new MqttConnectionStatusChangedEventArgs(false, e.ReasonString, _reconnectAttempts));
                    _logger.Debug("断开连接事件已触发");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "处理MQTT断开连接事件失败");
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 消息接收事件处理
        /// </summary>
        private Task OnApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            try
            {
                string topic = e.ApplicationMessage.Topic;
                byte[] payload = e.ApplicationMessage.PayloadSegment.Array;
                string payloadString = Encoding.UTF8.GetString(payload);

                _logger.Debug($"收到来自主题 {topic} 的消息: {payloadString}");

                // 触发消息接收事件
                OnMessageReceived(new MqttMessageReceivedEventArgs(topic, payload, payloadString));
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "处理MQTT消息接收事件失败");
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 触发连接状态变更事件
        /// </summary>
        protected virtual void OnConnectionStatusChanged(MqttConnectionStatusChangedEventArgs e)
        {
            try
            {
                _logger.Debug($"开始触发ConnectionStatusChanged事件: IsConnected={e.IsConnected}, DisconnectReason={e.DisconnectReason}, ReconnectAttempts={e.ReconnectAttempts}");
                
                if (ConnectionStatusChanged != null)
                {
                    ConnectionStatusChanged.Invoke(this, e);
                    _logger.Debug("ConnectionStatusChanged事件已触发");
                }
                else
                {
                    _logger.Warn("ConnectionStatusChanged事件未注册任何处理程序");
                }
            }
            catch (Exception ex)
            {
                _logger.Error($"触发ConnectionStatusChanged事件时发生错误: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 触发消息接收事件
        /// </summary>
        protected virtual void OnMessageReceived(MqttMessageReceivedEventArgs e)
        {
            MessageReceived?.Invoke(this, e);
        }

        /// <summary>
        /// 创建断开连接消息
        /// </summary>
        private byte[] CreateDisconnectMessage()
        {
            var disconnectModel = new DisconnectModel
            {
                DeviceCode = _options.DeviceCode,
                Payload = new DisconnectPayloadModel
                {
                    Reason = "unexpected_disconnect",
                    LastStatus = new Dictionary<string, object>
                    {
                        { "memoryUsage", GetMemoryUsage() },
                        { "cpuUsage", GetCpuUsage() }
                    }
                }
            };

            string json = Utils.Common.JsonHelper.Serialize(disconnectModel);
            return Encoding.UTF8.GetBytes(json);
        }

        /// <summary>
        /// 获取内存使用率
        /// </summary>
        private double GetMemoryUsage()
        {
            try
            {
                var metrics = Utils.Common.SystemInfo.GetMemoryUsage();
                return metrics.UsagePercentage;
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 获取CPU使用率
        /// </summary>
        private double GetCpuUsage()
        {
            try
            {
                return Utils.Common.SystemInfo.GetCpuUsage();
            }
            catch
            {
                return 0;
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            try
            {
                _logger.Info("开始释放MQTT客户端资源");
                
                // 清理事件订阅
                if (_managedClient != null)
                {
                    _logger.Debug("清理MQTT客户端事件订阅");
                    try
                    {
                        _managedClient.ConnectedAsync -= OnConnectedAsync;
                        _managedClient.DisconnectedAsync -= OnDisconnectedAsync;
                        _managedClient.ApplicationMessageReceivedAsync -= OnApplicationMessageReceivedAsync;
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn($"清理MQTT客户端事件订阅时发生错误: {ex.Message}");
                    }
                }
                
                if (_managedClient != null)
                {
                    // 尝试停止客户端，使用任务等待但设置超时
                    _logger.Debug("停止MQTT客户端");
                    try
                    {
                        var stopTask = _managedClient.StopAsync();
                        
                        // 设置较短的超时时间，避免界面卡住
                        if (!stopTask.Wait(1000))
                        {
                            _logger.Warn("停止MQTT客户端超时，将强制释放资源");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Warn($"停止MQTT客户端时发生错误: {ex.Message}，将强制释放资源");
                    }
                    
                    // 无论上面的操作是否成功，都尝试释放资源
                    try
                    {
                        _managedClient.Dispose();
                        _logger.Debug("MQTT客户端已释放");
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"释放MQTT客户端时发生错误: {ex.Message}");
                    }
                    finally
                    {
                        _managedClient = null;
                    }
                }

                // 释放连接锁
                try
                {
                    _connectionLock?.Dispose();
                    _logger.Debug("连接锁已释放");
                }
                catch (Exception ex)
                {
                    _logger.Error($"释放连接锁时发生错误: {ex.Message}");
                }
                
                _logger.Info("MQTT客户端资源释放完成");
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "释放MQTT客户端资源时发生未处理的异常");
            }
        }
    }

    /// <summary>
    /// MQTT连接状态变更事件参数
    /// </summary>
    public class MqttConnectionStatusChangedEventArgs : EventArgs
    {
        /// <summary>
        /// 是否已连接
        /// </summary>
        public bool IsConnected { get; }

        /// <summary>
        /// 断开连接原因
        /// </summary>
        public string DisconnectReason { get; }

        /// <summary>
        /// 重连尝试次数
        /// </summary>
        public int ReconnectAttempts { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="isConnected">是否已连接</param>
        /// <param name="disconnectReason">断开连接原因</param>
        /// <param name="reconnectAttempts">重连尝试次数</param>
        public MqttConnectionStatusChangedEventArgs(bool isConnected, string disconnectReason = null, int reconnectAttempts = 0)
        {
            IsConnected = isConnected;
            DisconnectReason = disconnectReason;
            ReconnectAttempts = reconnectAttempts;
        }
    }

    /// <summary>
    /// MQTT消息接收事件参数
    /// </summary>
    public class MqttMessageReceivedEventArgs : EventArgs
    {
        /// <summary>
        /// 主题
        /// </summary>
        public string Topic { get; }

        /// <summary>
        /// 消息内容（字节数组）
        /// </summary>
        public byte[] Payload { get; }

        /// <summary>
        /// 消息内容（字符串）
        /// </summary>
        public string PayloadString { get; }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="topic">主题</param>
        /// <param name="payload">消息内容（字节数组）</param>
        /// <param name="payloadString">消息内容（字符串）</param>
        public MqttMessageReceivedEventArgs(string topic, byte[] payload, string payloadString)
        {
            Topic = topic;
            Payload = payload;
            PayloadString = payloadString;
        }
    }
}